<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>cookie使用</h1>
    <!-- <script src="./utils.js"></script> -->
    <script>
      document.cookie = "user=Tans";
      document.cookie = "user2 = sheng";
      document.cookie = "user3 = xiaowang";

      // 设置cookie的key value domain Path expires
      // domain 默认为 '' ; 自动设置为当前页面的域名
      // path 默认为'' ; 自动设置为当前页面的地址中的路径
      // expires默认为'' ; 自动设置为session（会话）

      let d = new Date();
      d.setMinutes(d.getMinutes() + 60 * 24);
      console.log(d);

      document.cookie =
        " user4=laowang; domain=127.0.0.1; path=/; expires=" + d; //字符串拼接

      // 设置cookie的函数
      function setCookie(option) {
        let { key, val, domain = "", path = "", exp = "" } = option;

        // 用来存储事件的变量
        let d = "";
        // 判断exp里面有值
        if (exp) {
          d = new Date();
          d.setMinutes(d.getMinutes() + exp);
        }

        // 设置cookie
        document.cookie = `${key}=${val}; domain=${domain}; path=${path}; expires=${d}`;
      }

      setCookie({
        key: "user5",
        val: "xiaomin",
        domain: "localhost",
        path: "/",
        exp: 60 * 8,
      });
      setCookie({
        key: "user6",
        val: "xiaolan",
      });

      // 获取cookie
      console.log(document.cookie); //得到的cookie的键值对这个数组

      //需求:获取user3的值

      function getCookie(key) {
        let arr1 = document.cookie.split("; ");
        // console.log(arr1);   
        console.log(arr1);
        let result = null;
        arr1.forEach((val) => {
          console.log(val);
          let arr2 = val.split("=");
          if (arr2[0] === key) {
            result = arr2[1];
          }
        });

        // 返回结果
        return result;
      }

      console.log(getCookie('user3'));

    // 删除cookie
    // 当coolkie过期的时候,浏览器自动删除cookie
    function removeCookie(key,Path){
        setCookie({
            key:key,
            val:123,
            path:Path,
            exp:-60*24, //设置过期时间;
        })
    }   

    removeCookie('user5','/');
    removeCookie('user6','/static');
    </script>
  </body>
</html>
